﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Text.Json;
using System.Linq;

namespace SignalRDemo.Hubs
{
    public class ChatHub : Hub
    {
        // 在线用户
        public static ConcurrentDictionary<string, string> OnLineUsers = new ConcurrentDictionary<string, string>();

        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            // 根据ConnectionId反查userid
            var dic = OnLineUsers.FirstOrDefault(x => x.Value.Equals(Context.ConnectionId));
            OnLineUsers.TryRemove(dic.Key, out string connectionId);
            Console.WriteLine($"{dic.Key}:{Context.ConnectionId}已断开");
            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="user">用户名称</param>
        /// <param name="message">信息</param>
        /// <returns></returns>
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="token">用户Token</param>
        /// <returns></returns>
        public async Task Login(string token)
        {
            // 根据token进行鉴权，获取用户信息
            // coding...
            string userId = token;

            OnLineUsers.AddOrUpdate(userId, Context.ConnectionId, (key, value) =>
            {
                return Context.ConnectionId;
            });
            Console.WriteLine($"{userId}:{Context.ConnectionId}已对应");
            await Clients.Caller.SendAsync("LoginComplete", JsonSerializer.Serialize(new { rtnCode = 0, rtnMsg = "Success", userId = userId }));
        }

    }
}
